import tkinter as tk
import platform


class MessageDialog:
    """现代化风格的自定义消息对话框组件"""

    def __init__(self, parent: tk.Tk):
        """初始化消息对话框

        Args:
            parent: 父窗口
        """
        self.parent = parent

    def show(
        self,
        title: str,
        message: str,
        msg_type: str = "info",
        width: int = 400,
        height: int = 200,
    ) -> None:
        """显示消息对话框

        Args:
            title: 对话框标题
            message: 消息内容
            msg_type: 消息类型 ('info', 'warning', 'error', 'success')
            width: 对话框宽度
            height: 对话框高度
        """
        # 获取主窗口位置和大小
        self.parent.update_idletasks()
        x = self.parent.winfo_x()
        y = self.parent.winfo_y()
        parent_width = self.parent.winfo_width()
        parent_height = self.parent.winfo_height()

        # 创建对话框窗口
        dialog = tk.Toplevel(self.parent)
        dialog.title("")
        dialog.resizable(False, False)
        dialog.grab_set()
        dialog.overrideredirect(True)  # 移除标题栏，创建自定义样式

        # 消息类型配置
        type_config = {
            "info": {
                "color": "#2196F3",
                "bg": "#E3F2FD",
                "icon": "💡",
                "title_color": "#1976D2",
            },
            "warning": {
                "color": "#FF9800",
                "bg": "#FFF3E0",
                "icon": "⚠️",
                "title_color": "#F57C00",
            },
            "error": {
                "color": "#F44336",
                "bg": "#FFEBEE",
                "icon": "❌",
                "title_color": "#D32F2F",
            },
            "success": {
                "color": "#4CAF50",
                "bg": "#E8F5E8",
                "icon": "✅",
                "title_color": "#388E3C",
            },
        }

        config = type_config.get(msg_type, type_config["info"])

        # 主容器
        main_container = tk.Frame(dialog, bg="white", relief="solid", bd=1)
        main_container.pack(fill="both", expand=True)

        # 顶部彩色条
        top_bar = tk.Frame(main_container, bg=config["color"], height=4)
        top_bar.pack(fill="x")

        # 内容区域
        content_area = tk.Frame(main_container, bg="white")
        content_area.pack(fill="both", expand=True, padx=25, pady=20)

        # 标题区域
        title_frame = tk.Frame(content_area, bg="white")
        title_frame.pack(fill="x", pady=(0, 15))

        # 图标
        icon_label = tk.Label(
            title_frame,
            text=config["icon"],
            font=("Segoe UI Emoji", 20),
            bg="white",
            fg=config["color"],
        )
        icon_label.pack(side="left")

        # 标题文本
        title_label = tk.Label(
            title_frame,
            text=title,
            font=("Microsoft YaHei UI", 14, "bold"),
            bg="white",
            fg=config["title_color"],
        )
        title_label.pack(side="left", padx=(10, 0))

        # 消息内容
        message_frame = tk.Frame(content_area, bg="white")
        message_frame.pack(fill="both", expand=True, pady=(0, 20))

        message_label = tk.Label(
            message_frame,
            text=message,
            font=("Microsoft YaHei UI", 10),
            bg="white",
            fg="#424242",
            wraplength=width - 80,
            justify="left",
        )
        message_label.pack(anchor="w")

        # 按钮区域
        button_frame = tk.Frame(content_area, bg="white")
        button_frame.pack(fill="x")

        def close_dialog():
            dialog.destroy()

        # 自定义按钮样式
        button_container = tk.Frame(button_frame, bg="white")
        button_container.pack(anchor="e")

        ok_button = tk.Button(
            button_container,
            text="确定",
            command=close_dialog,
            font=("Microsoft YaHei UI", 9),
            bg=config["color"],
            fg="white",
            relief="flat",
            padx=20,
            pady=8,
            cursor="hand2",
            activebackground=self._darken_color(config["color"]),
            activeforeground="white",
            bd=0,
        )
        ok_button.pack()

        # 按钮悬停效果
        def on_enter(e):
            ok_button.config(bg=self._darken_color(config["color"]))

        def on_leave(e):
            ok_button.config(bg=config["color"])

        ok_button.bind("<Enter>", on_enter)
        ok_button.bind("<Leave>", on_leave)

        # 设置对话框大小和位置
        dialog.geometry(f"{width}x{height}")

        # 计算居中位置
        pos_x = x + (parent_width // 2) - (width // 2)
        pos_y = y + (parent_height // 2) - (height // 2)

        # 确保不超出屏幕边界
        screen_width = dialog.winfo_screenwidth()
        screen_height = dialog.winfo_screenheight()
        pos_x = max(10, min(pos_x, screen_width - width - 10))
        pos_y = max(10, min(pos_y, screen_height - height - 10))

        dialog.geometry(f"{width}x{height}+{pos_x}+{pos_y}")

        # 添加阴影效果（Windows平台）
        if platform.system() == "Windows":
            try:
                import ctypes
                from ctypes import wintypes

                hwnd = dialog.winfo_id()
                # 设置窗口阴影
                ctypes.windll.dwmapi.DwmSetWindowAttribute(
                    hwnd, 2, ctypes.byref(ctypes.c_int(2)), ctypes.sizeof(ctypes.c_int)
                )
            except:
                pass  # 如果失败就忽略阴影效果

        # 键盘绑定
        dialog.bind("<Escape>", lambda e: close_dialog())
        dialog.bind("<Return>", lambda e: close_dialog())
        dialog.bind("<Button-1>", lambda e: dialog.focus_set())

        # 设置焦点
        dialog.focus_set()
        ok_button.focus_set()

        # 淡入动画效果
        dialog.attributes("-alpha", 0.0)
        dialog.update()

        def fade_in(alpha=0.0):
            alpha += 0.1
            if alpha <= 1.0:
                dialog.attributes("-alpha", alpha)
                dialog.after(20, lambda: fade_in(alpha))
            else:
                dialog.attributes("-alpha", 1.0)

        fade_in()

    def _darken_color(self, color: str, factor: float = 0.8) -> str:
        """将颜色变暗"""
        if color.startswith("#"):
            color = color[1:]

        try:
            r = int(color[0:2], 16)
            g = int(color[2:4], 16)
            b = int(color[4:6], 16)

            r = int(r * factor)
            g = int(g * factor)
            b = int(b * factor)

            return f"#{r:02x}{g:02x}{b:02x}"
        except:
            return color

    @staticmethod
    def show_info(parent: tk.Tk, title: str, message: str, **kwargs):
        """显示信息对话框的静态方法"""
        dialog = MessageDialog(parent)
        dialog.show(title, message, "info", **kwargs)

    @staticmethod
    def show_warning(parent: tk.Tk, title: str, message: str, **kwargs):
        """显示警告对话框的静态方法"""
        dialog = MessageDialog(parent)
        dialog.show(title, message, "warning", **kwargs)

    @staticmethod
    def show_error(parent: tk.Tk, title: str, message: str, **kwargs):
        """显示错误对话框的静态方法"""
        dialog = MessageDialog(parent)
        dialog.show(title, message, "error", **kwargs)

    @staticmethod
    def show_success(parent: tk.Tk, title: str, message: str, **kwargs):
        """显示成功对话框的静态方法"""
        dialog = MessageDialog(parent)
        dialog.show(title, message, "success", **kwargs)
